const toggleButton = document.getElementById('toggleButton');

// 更新按钮文字和状态
function updateButtonText(isActive) {
  const switchLabel = document.querySelector('.switch-label');
  toggleButton.checked = isActive;
  switchLabel.textContent = isActive ? '护眼' : '护眼已关';
}

// 初始化时从存储中获取颜色设置
chrome.storage.local.get(['color', 'opacity'], function(result) {
  if (result.color) {
    document.getElementById('colorPicker').value = result.color;
  }
  if (result.opacity) {
    document.getElementById('opacitySlider').value = result.opacity;
    document.getElementById('opacityValue').textContent = result.opacity + '%';
  }
});

// 获取当前页面的护眼模式状态
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
  if (tabs[0]) {
    chrome.tabs.sendMessage(tabs[0].id, { action: 'getState' }, function(response) {
      if (response) {
        updateButtonText(response.isActive);
      }
    });
  }
});

// 颜色选择器变化事件
document.getElementById('colorPicker').addEventListener('change', (e) => {
  const color = e.target.value;
  const opacity = document.getElementById('opacitySlider').value;
  saveColorSettings(color, opacity);
});

// 透明度滑块变化事件
document.getElementById('opacitySlider').addEventListener('input', (e) => {
  const opacity = e.target.value;
  document.getElementById('opacityValue').textContent = opacity + '%';
  const color = document.getElementById('colorPicker').value;
  saveColorSettings(color, opacity);
});

// 保存颜色设置
function saveColorSettings(color, opacity) {
  chrome.storage.local.set({
    color: color,
    opacity: opacity
  });
  
  // 通知当前标签页更新颜色
  chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {
      action: 'updateColor',
      color: color,
      opacity: opacity
    });
  });
}

// 开关按钮点击事件
toggleButton.addEventListener('click', async () => {
  try {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    chrome.tabs.sendMessage(tab.id, { action: 'toggle' });
  } catch (error) {
    console.log('发生错误：', error);
  }
}); 
